//
//  UIImageViewExtension.swift
//  Jock
//
//  Created by HD on 15/3/14.
//  Copyright (c) 2015年 Haidy. All rights reserved.
//

import UIKit

extension UIImageView {
    
    func setImage(urlString: String, placeHolder: UIImage!) {
        setImage(urlString, placeHolder: placeHolder, callBack: nil)
    }
    
    func setImage(urlString: String, placeHolder: UIImage!, callBack: ((image: UIImage) -> Void)!) {
        var url = NSURL(string: urlString)
        var cacheFilename = url!.lastPathComponent
        var cachePath = FileUtil.getCachePath("imageCache", fileName: cacheFilename!)
        var image = FileUtil.loadImageFromPath(cachePath)
//        println(placeHolder.size)
        if image != nil {
            self.image = image
            if callBack != nil {
                callBack(image: image)
            }
        } else {    // 网络获取image
            self.image = placeHolder
            ThreadUtil.childThread({ () -> Void in
                let data = NSData(contentsOfURL: url!)
                if data != nil {
                    image = UIImage(data: data!)
                    ThreadUtil.mainThread({ () -> Void in
                        if image != nil {
                            self.image = image
                            if callBack != nil {
                                callBack(image: image)
                            }
                            FileUtil.imageCacheToPath(cachePath, image: data!)
                        }
                    })
                }
            })
        }
    }
}
